<?php
/*
模型层 -- 用户
*/

class User
{
	private $db;

	public function __construct($db)
	{
		$this->db = $db;
	}

	// 根据邮箱查找用户
	public function findByEmail($email)
	{
		$stmt = $this->db->prepare("SELECT * FROM users WHERE email = ?");
		$stmt->execute([$email]);
		return $stmt->fetch(PDO::FETCH_ASSOC);
	}

	// 验证密码
	public function verifyPassword($user, $password)
	{
		// return password_verify($password, $user['password']); //	哈希密码验证

		return $user['password'] === $password;
	}


	//  创建用户
	public function create($email, $password)
	{
		// 检查邮箱是否已存在
		if ($this->findByEmail($email)) {
			throw new Exception('Email already registered');
		}

		// 生成初始用户名
		$username = 'user_' . uniqid();

		// 存储密码
		$stmt = $this->db->prepare("INSERT INTO users (email, password, username ) VALUES (?, ?, ?)");
		$result = $stmt->execute([$email, $password, $username]);

		if (!$result) {
			throw new Exception('Registration failed');
		}

		return $this->findByEmail($email);
	}

}
?>